// pages/announcement_list/announcement_list.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    announcements: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    const app = getApp(); // 获取小程序实例
    const dormitoryId = app.globalData.dormitoryId; 
    console.log(dormitoryId);
    // 获取数据库中所有物品信息
    db.collection("announcement_db").where({dormitoryId:dormitoryId}).get().then(res => {
      this.setData({
        announcements: res.data
      })
    })
  },

  editAnnouncement: function (e) {
    const announcementId = e.currentTarget.dataset.id;
    const selectedAnnouncement = this.data.announcements.filter(announcement => announcement._id === announcementId)[0];
    console.log(selectedAnnouncement);
    wx.navigateTo({
      url: `/pages/announcement/announcement?announcement=${JSON.stringify(selectedAnnouncement)}&id=${selectedAnnouncement._id}`,
    });
  },

  onShow: function () {
    const app = getApp(); // 获取小程序实例
    const dormitoryId = app.globalData.dormitoryId; 
    console.log(dormitoryId);
    // 获取数据库中所有物品信息
    db.collection("announcement_db").where({dormitoryId:dormitoryId}).get().then(res => {
      this.setData({
        announcements: res.data
      })
    })
  },

  addAnnouncement: function () {
    wx.navigateTo({
      url: '/pages/announcement/announcement'
    });
  },

  //删除公告
  deleteAnnouncement(e) {
    if (!e) return;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除该公告吗？',
      success: (res) => {
        if (res.confirm) {
          // 用户点击确定，执行删除操作
          const announcementId = e.currentTarget.dataset.id;
          const selectedAnnouncement = this.data.announcements.filter(announcement => announcement._id === announcementId)[0];
          db.collection('announcement_db').doc(selectedAnnouncement._id).remove({
            success: () => {
              wx.showToast({
                title: '删除成功'
              });
              this.onShow()
            },
            fail: () => {
              wx.showToast({
                title: '删除失败'
              });
            }
          });
        }
      }
    });
  }
})